package org.ala.tiktools.rocketmq.producer;

import org.ala.tiktools.rocketmq.annotations.ProducerService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

/**
 * @author ala
 * @date 2024-12-05 12:41
 */
public class ProducerServiceFactoryBean implements FactoryBean<Object>, ApplicationContextAware {


    /**
     *  被代理的接口类型
     */
    protected Class<? extends ProducerService> type;

    protected ApplicationContext applicationContext;


    @Override
    public Object getObject() throws Exception {
        //  构造ProducerExecutor
        Map<Method, ProducerExecutor> methodMapper = RocketMQProducerInitializer.getInstance().parse(type, applicationContext);

        //  构造代理执行器
        ProducerServiceInvocationHandler handler = new ProducerServiceInvocationHandler();
        handler.executorMapper = methodMapper;

        return Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type}, handler);
    }


    @Override
    public Class<?> getObjectType() {
        return type;
    }


    public Class<? extends ProducerService> getType() {
        return type;
    }
    public void setType(Class<? extends ProducerService> type) {
        this.type = type;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
